package com.clinic.shiro;

import com.clinic.entity.ClinicPerms;
import com.clinic.entity.ClinicRoles;
import com.clinic.entity.ClinicUsers;
import com.clinic.service.ClinicUsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("UserRealm")
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private ClinicUsersService usersService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        String user = getAvailablePrincipal(principalCollection).toString();

        System.out.println(user);

        List<ClinicRoles> roles = usersService.getRolesByUsername(user);

        for (ClinicRoles r : roles) {
            info.addRole(r.getCrname());
        }

        List<ClinicPerms> permissions = usersService.getPermissionByUsername(user);

        for (ClinicPerms p : permissions) {
            info.addStringPermission(p.getCpname());
        }

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        AuthenticationInfo info = null;

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String username = token.getUsername();
        char[] passchar = token.getPassword();
        String password = new String(passchar);

        ClinicUsers u = usersService.login(username, password);

        if(u != null){
            info = new SimpleAuthenticationInfo(username, password, getName());
        }

        return info;
    }
}
